All files / src/app/api/admin/support/chat/[conversationId] route.ts

0% Statements 0/198
100% Branches 0/0
0% Functions 0/1
0% Lines 0/198

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199                                                                                                                                                                                                                                                                                                                                                                                                             
export const dynamic = 'force-dynamic';

/**
 * Admin Chat Conversation API
 * GET /api/admin/support/chat/[conversationId] - Get conversation with context
 * PATCH /api/admin/support/chat/[conversationId] - Update conversation
 * POST /api/admin/support/chat/[conversationId] - Send message as agent
 */

import { NextRequest, NextResponse } from 'next/server';
import { Session } from 'next-auth';
import {
  withAdmin,
  withErrorHandling,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse,
  RouteContext,
} from '@/lib/api';
import { ChatService } from '@/services';
import { z } from 'zod';

// ============================================================================
// VALIDATION
// ============================================================================

const UpdateConversationSchema = z.object({
  action: z.enum(['assign', 'resolve', 'close', 'hold', 'transfer', 'priority']),
  resolution: z.string().optional(),
  reason: z.string().optional(),
  toAgentId: z.number().optional(),
  priority: z.number().min(0).max(3).optional(),
  tags: z.array(z.string()).optional(),
});

const SendMessageSchema = z.object({
  content: z.string().min(1, 'Message content is required').max(5000),
  contentType: z
    .enum(['TEXT', 'IMAGE', 'FILE', 'PRODUCT_CARD', 'ORDER_CARD', 'QUICK_REPLIES'])
    .optional()
    .default('TEXT'),
  attachments: z.array(z.unknown()).optional(),
});

// ============================================================================
// HANDLERS
// ============================================================================

/**
 * GET /api/admin/support/chat/[conversationId]
 * Get conversation with full context for agents
 */
async function handleGet(
  _request: NextRequest,
  context: RouteContext | undefined
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { conversationId } = await context!.params!;

  const conversation = await ChatService.getConversationWithContext(conversationId);

  if (!conversation) {
    throw ApiError.notFound('Conversation not found');
  }

  // Mark customer messages as read
  await ChatService.markMessagesAsRead(conversationId, 'agent');

  return NextResponse.json({
    success: true,
    data: conversation,
  });
}

/**
 * PATCH /api/admin/support/chat/[conversationId]
 * Update conversation (assign, resolve, close, etc.)
 */
async function handlePatch(
  request: NextRequest,
  context: RouteContext | undefined,
  session: Session
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { conversationId } = await context!.params!;
  const body = await request.json();

  // Validate request body
  const parseResult = UpdateConversationSchema.safeParse(body);
  if (!parseResult.success) {
    throw ApiError.validation(
      'Invalid request data',
      parseResult.error.issues
    );
  }

  const { action, resolution, reason, toAgentId, priority, tags } = parseResult.data;
  const agentId = session.user.id;

  switch (action) {
    case 'assign':
      await ChatService.assignConversation(conversationId, agentId);
      break;

    case 'resolve':
      await ChatService.resolveConversation(conversationId, resolution);
      break;

    case 'close':
      await ChatService.closeConversation(conversationId);
      break;

    case 'hold':
      await ChatService.holdConversation(conversationId, reason);
      break;

    case 'transfer':
      if (!toAgentId) {
        throw ApiError.badRequest('Target agent ID is required for transfer');
      }
      await ChatService.transferConversation(
        conversationId,
        agentId,
        toAgentId,
        reason
      );
      break;

    case 'priority':
      if (priority === undefined) {
        throw ApiError.badRequest('Priority value is required');
      }
      await ChatService.setPriority(conversationId, priority);
      break;

    default:
      throw ApiError.badRequest('Invalid action');
  }

  // Handle tags if provided
  if (tags && tags.length > 0) {
    await ChatService.addTags(conversationId, tags);
  }

  // Get updated conversation
  const conversation = await ChatService.getConversationWithContext(conversationId);

  return NextResponse.json({
    success: true,
    data: conversation,
  });
}

/**
 * POST /api/admin/support/chat/[conversationId]
 * Send message as agent
 */
async function handlePost(
  request: NextRequest,
  context: RouteContext | undefined,
  session: Session
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { conversationId } = await context!.params!;
  const body = await request.json();

  // Validate request body
  const parseResult = SendMessageSchema.safeParse(body);
  if (!parseResult.success) {
    throw ApiError.validation(
      'Invalid request data',
      parseResult.error.issues
    );
  }

  const { content, contentType, attachments } = parseResult.data;
  const agentId = session.user.id;

  // Send the message
  const message = await ChatService.sendMessage({
    conversationId,
    senderId: agentId,
    senderType: 'AGENT',
    content,
    contentType,
    attachments: attachments as never,
  });

  return NextResponse.json({
    success: true,
    data: message,
  });
}

// ============================================================================
// EXPORTS
// ============================================================================

export const GET = withErrorHandling(withAdmin(handleGet));
export const PATCH = withErrorHandling(withAdmin(handlePatch));
export const POST = withErrorHandling(withAdmin(handlePost));